package net.livingflow.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.livingflow.Constants;
import net.livingflow.model.Pack;

import org.springframework.stereotype.Service;

/**
 * @author xueqiang.mi
 * @since 2010-11-27
 */
@Service
public class PackService extends BaseService {

	public void add(Pack p) {
		Date now = new Date();
		p.setCrtDate(now);
		p.setModDate(now);

		save(p);
	}

	public void createDefaultPackForUSer(String owner) {
		createPackForUser(Constants.DEFAULT_PACK_NAME, owner);
	}

	public void createPackForUser(String name, String owner) {
		Pack p = new Pack();
		p.setName(name);
		p.setOwner(owner);

		add(p);
	}

	public void del(Long id) {
		delete(Pack.class, id);
	}

	public Pack get(Long id) {
		return get(Pack.class, id);
	}

	public Pack getDefaultPack(String owner) {
		return getPack(Constants.DEFAULT_PACK_NAME, owner);
	}

	@SuppressWarnings("unchecked")
	public Pack getPack(String name, String owner) {
		PersistenceManager pm = PMF.get();
		Query query = pm.newQuery(Pack.class);
		query.setFilter("name == '" + name + "' && owner == '" + owner + "'");
		Collection<Pack> c = (Collection<Pack>) query.execute();
		if (c != null && c.size() == 1) {
			return (Pack) c.toArray()[0];
		}
		return null;
	}

	public List<Pack> list() {
		return list(Pack.class);
	}

	@SuppressWarnings("unchecked")
	public List<Pack> getByUser(String userName) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Pack.class);
			query.setFilter("owner == :owner");
			query.setOrdering("rating desc");
			Collection<Pack> c = pm.detachCopyAll((Collection<Pack>) query.execute(userName));
			return new ArrayList<Pack>(c);
		} finally {
			pm.close();
		}
	}
}
